package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements UserLoginService {

    @Override
    public ResponseResult login(AdUserDto dto) {
        //dto  用户名 密码 任意为空 返回错误
       if(dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) return errorParam;
         //返回一条数据
         AdUser one = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(one==null) return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");

        String tablepwd = one.getPassword(); //表里保存的密码 (加密)
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());//表单传过来的密码 需要密码+盐
        //其实没有登录的事，就是前端传了个参数，后端校验了一下
        if(tablepwd.equals(s)){
            //登录成功后，要返回token了
            Map<String,Object> resultMap = new HashMap<>();
            //token的用户id从表中取
            resultMap.put("token", AppJwtUtil.getToken(Long.valueOf(one.getId())));
            //不能返回密码,和盐，这样子很容易让他人推断出来加密算法
            one.setPassword("");
            one.setSalt("");
            //返回当前用户信息
            resultMap.put("user",one);
            return ResponseResult.okResult(resultMap);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
    }
}
